﻿using Common.Extensions;
using Common.Utility;
using Interface.Volcengine.DTO;
using Interface.WanX.DTO.Turbo;
using System;

namespace Interface.WanX
{
    public class WanXApi
    {
        private readonly IHttpClientFactory _httpClientFactory;

        private string ApiUrl = $"{AppSetting.GetAppSetting("WanX:Url")}";

        public WanXApi(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<List<TurboResult>> TurboAsync(string prompt)
        {
            var requestBody = new TurboRequest
            {
                Input = new TurboInput
                {
                    Prompt = prompt,
                }
            };

            var headers = new Dictionary<string, string>
            {
                { "Authorization", $"Bearer {AppSetting.GetAppSetting("WanX:API-Key")}" },
                { "X-DashScope-Async", "enable" }
            };

            var _httpClient = _httpClientFactory.CreateClient();
            var httpResponse = await _httpClient.HttpPost<WanXResponseBase<TaskResponse>>($"{ApiUrl}{AppSetting.GetAppSetting("WanX:Turbo:ActionUrl")}", headers, requestBody);
            if (!httpResponse.IsSuccess || httpResponse.Data == null)
            {
                throw new Exception(httpResponse.Msg);
            }
            if (httpResponse.Data.Data == null && !string.IsNullOrWhiteSpace(httpResponse.Data.Message))
            {
                throw new Exception(httpResponse.Data.Message);
            }
            var taskId = httpResponse.Data.Data.TaskId;
            for (int i = 0; i < 10; i++)
            {
                var httpTaskResponse = await _httpClient.HttpGet<WanXResponseBase<TurboResponse>>($"{ApiUrl}{AppSetting.GetAppSetting("WanX:Turbo:TaskUrl")}{taskId}", headers);
                if (!httpTaskResponse.IsSuccess || httpTaskResponse.Data == null)
                {
                    throw new Exception(httpResponse.Msg);
                }
                if (httpTaskResponse.Data.Data == null && !string.IsNullOrWhiteSpace(httpTaskResponse.Data.Message))
                {
                    throw new Exception(httpTaskResponse.Data.Message);
                }
                if (httpTaskResponse.Data.Data.IsFailed)
                {
                    return null;
                }
                if (httpTaskResponse.Data.Data.IsSuccess)
                {
                    return httpTaskResponse.Data.Data.Results;
                }

                Thread.Sleep(5000);
            }
            return null;
        }
    }
}
